import requests
import hashlib
import urllib.parse
import time

def driving_route_planning(AK, SK, origin, destination):
    base_url = "https://api.map.baidu.com/direction/v2/driving"
  
    # 生成SN签名
    query = {
        'origin': origin,
        'destination': destination,
        'ak': AK,
        'timestamp': str(int(time.time())),
        'output': 'json'
    }
    encoded_str = urllib.parse.urlencode(query)
    raw_str = f"/direction/v2/driving?{encoded_str}{SK}"
    sn = hashlib.md5(urllib.parse.quote_plus(raw_str).encode()).hexdigest()
  
    # 带SN的请求URL
    url = f"{base_url}?{encoded_str}&sn={sn}"
  
    response = requests.get(url)
    result = response.json()
    routes = result["result"]["routes"]

    #按 距离/时间/分数 排序 (distance/duration/score)
    routes.sort(key = lambda x: x["distance"])
    route = routes[0]

    distance = route["distance"]
    duration = route["duration"]
    score = route["score"]
    paths = "|".join(list(map(lambda x: x["path"], route["steps"])))
    return distance, duration, score, paths
